package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"novel-start/models/cache"
	"novel-start/models/mysql"
	"novel-start/pkg"
	"time"

	"novel-start/novelrpc/internal/svc"
	"novel-start/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *novelrpc.LoginRequest) (*novelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	user := &mysql.User{
		Mobile:    in.Mobile,
		Password:  pkg.Md5(in.Password),
		HeadImage: "http://t4kafhsbw.hn-bkt.clouddn.com/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F1.jpg",
		NickName:  fmt.Sprintf("书友%d%d", time.Now().Unix(), rand.Intn(1000)),
	}

	if in.LoginType == 1 {
		if pkg.Md5(in.Password) != user.Password {
			return nil, errors.New("密码错误")
		}
	} else {
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

		if result == "" {
			return nil, errors.New("验证码还未发送")
		}

		if in.SmsCode != result {
			return nil, errors.New("验证码错误,请重新输入")
		}
	}

	if err := user.UserFirstOrCreate(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}

	return &novelrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
